package com.emily.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.emily.test.constant.ReturnValueConstants;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.RCompanyRole;
import com.emily.test.model.TCompany;
import com.emily.test.model.TRole;
import com.emily.test.model.TUser;
import com.emily.test.service.*;
import com.emily.test.utils.ConstentUtil;
import com.emily.test.utils.HeaderUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "tUserRoleController")
@Api(value = "TUserRoleApi", description = "TUserRole接口类", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class TUserRoleController {

    private Logger logger = LoggerFactory.getLogger(TUserRoleController.class);

    @Autowired
    private TUserRoleService tUserRoleService;

    @Autowired
    private TUserService tUserService;

    @Autowired
    private RoleService tRoleService;

    @Autowired
    private RCompanyRoleService rCompanyRoleService;

    @Autowired
    private RoleService roleService;
    @Autowired
    private RedisService redisService;


    /**
     * 插入用户与角色关联表信息
     * @param jsonObject 包含用户ID（userId）与角色（roleIds）关联表集合 ，其中userId格式为Integer，roleIds格式为List集合
     * @return
     */
    @ApiOperation(value="插入用户与角色关联表信息", notes="插入用户与角色关联表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true),
            @ApiImplicitParam(name = "roleIds", value = "角色ID", required = true)
    })
    @PostMapping(value = "insertTUserRoleInfo")
    public ResponseResult insertTUserRoleInfo(@RequestBody JSONObject jsonObject){
        Map<String,Object> map=jsonObject.getInnerMap();
        try {
            int num=tUserRoleService.insertTUserRoleInfo(map);
            if(num==0){
                logger.error("未插入用户与角色关联表信息的数据,插入数据条数:{}",num);
                return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
            }
            logger.info("用户与角色关联表信息"+ReturnValueConstants.ADD_SUCCESS+"增加条数：{}",num);
            return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS,num);
        } catch (Exception e) {
            logger.error("插入用户与角色关联表的数据异常{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }

    /**
     *根据用户ID删除对应的角色ID
     * @param jsonObject 其中必须含有userId
     * @return
     */
    @ApiOperation(value="根据用户ID删除对应的角色ID", notes="根据用户ID删除对应的角色ID")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true)
    })
    @PostMapping(value = "deleteUserRoleByUserId")
    public ResponseResult deleteUserRoleByUserId(@RequestBody JSONObject jsonObject){
        Integer userId=jsonObject.getInteger("userId");
        if(ConstentUtil.isEmpty(userId)){
            logger.error("用户ID为空,用户ID={}",userId);
            return ResponseResult.fail("用户"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            int num= tUserRoleService.deleteUserRoleByUserId(userId);
            logger.info("根据用户ID删除相应的角色ID成功，删除的条数={}",num);
            return ResponseResult.success(ReturnValueConstants.DELATE_SUCCESS,num);
        } catch (Exception e) {
            logger.error("根据用户ID删除相应的角色ID失败,异常为:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.DELATE_FAILURE);
        }
    }

    /**
     * 根据用户ID更新用户与角色关系信息表
     * @param jsonObject 包含用户（userId）与角色（roleIds）关联表集合 ，其中userId格式为Integer，roleIds格式为List集合
     * @return
     */
    @ApiOperation(value="根据用户ID更新用户与角色关系信息表", notes="根据用户ID更新用户与角色关系信息表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true),
            @ApiImplicitParam(name = "roleIds", value = "角色ID")
    })
    @PostMapping(value = "updateUserRoleInfo")
    public ResponseResult updateUserRoleInfo(@RequestBody JSONObject jsonObject){
        Map<String,Object> map=jsonObject.getInnerMap();
//        String companyId=map.get("companyId") == null ? null : (String)map.get("companyId");
//        if(ConstentUtil.isEmpty(companyId)){
//            return ResponseResult.fail("更新失败，用户信息为空，请检查");
//        }
        Integer userId=Integer.parseInt(map.get("userId").toString());
        if(ConstentUtil.isEmpty(userId)){
            logger.error("用户ID不允许为空,userId={}",userId);
            return ResponseResult.fail("用户"+ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            //删除原有用户与角色的对应关系
            int delNum=tUserRoleService.deleteUserRoleByUserId(userId);
            logger.info("删除原有用户与角色的绑定关系成功，删除条数={}",delNum);

            //增加新的用户与角色的绑定关系，如果角色信息集合为空，则不需插入
            if(ConstentUtil.isEmpty((List<Integer>)map.get("roleIds"))){
                logger.info("角色信息集合为空，插入的用户与角色信息集合={}",map);
                return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS,0);
            }
            int addNum=tUserRoleService.insertTUserRoleInfo(map);

            logger.info("修改用户与角色的绑定关系成功，新增条数={}",addNum);
            return ResponseResult.success(ReturnValueConstants.UPDATE_SUCCESS,addNum);
        } catch (Exception e) {
            logger.error("更新t_user_role表失败,异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }

    /**
     * 根据用户ids查询角色信息
     * @param jsonObject
     * @return
     */
    @ApiOperation(value="根据用户ids查询角色信息", notes="t_user_role")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userIds", value = "用户IDs", required = true)
    })
    @PostMapping(value = "getUserRoleInfoByUserIds")
    public ResponseResult getUserRoleInfoByUserIds(@RequestBody JSONObject jsonObject){
        String userIds=jsonObject.getString("userIds");
        try {
            List<Map<String,Object>> tRoleList= tRoleService.selectTRoleInfoListByUserId(ConstentUtil.strToList(userIds));
            String[] strs = userIds.split(",");
            List all_list = new ArrayList();
            for (int j = 0; j < strs.length; j++) {
                HashMap<String, Object> hm = new HashMap<>();
                List list1 = new ArrayList();
                for (int i = 0; i < tRoleList.size(); i++) {
                    if(strs[j].equals(tRoleList.get(i).get("userId").toString())) {
                        hm.put("userId", strs[j]);
                        hm.put("userName", tRoleList.get(i).get("userName").toString());
                        hm.put("loginName", tRoleList.get(i).get("loginName").toString());
                        list1.add(tRoleList.get(i));
                        hm.put("data",list1);
                    }
                }
                if(hm.size()!=0){
                    all_list.add(hm);
                }
            }
            logger.info("查询t_role成功，list={}",all_list);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS,all_list);
        } catch (Exception e) {
            logger.error("查询t__role异常:{}",e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    /**
     * 根据用户ID获取用户信息以及所有的角色信息集合，其中用户已经有的角色信息添加selected=1属性，没有的则为selected=0.
     * @param jsonObject 包含用户（userId）与角色（roleIds）关联表集合 ，其中userId格式为Integer，roleIds格式为List集合
     * @return
     */
    @ApiOperation(value="根据用户ID获取用户信息以及所有的角色信息集合，其中用户已经有的角色信息添加selected=1" +
            "属性，没有的则为selected=0", notes="t_user_role")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true)
    })
    @PostMapping(value = "getUserAndAllRoleInfoByUserId")
    public ResponseResult getUserAndAllRoleInfoByUserId(@RequestBody JSONObject jsonObject, HttpServletRequest request){

        //获取登录人的信息
        String token = request.getHeader("token");
        System.out.println("token===="+token);
        Map<String,Object> userMap=  (Map<String,Object>)redisService.get(token);
        Integer companyId= (Integer) userMap.get("companyId");

        try {
            //用户ID
            Integer userId=jsonObject.getInteger("id");

            //根据用户ID获取用户信息
            TUser tUser= tUserService.getUserInfoById(userId);

            //获取用户已经存在的角色信息列表
            List list=new ArrayList();
            list.add(userId);
            List<Map<String,Object>> tRoleLists= tRoleService.selectTRoleInfoListByUserId(list);

            //获取所有启用的本公司下的角色信息,该接口需等公司接口实现完成后进行********

            List<Map<String,Object>> tRoleList=roleService.selectTRoleInfoListByCompanyId(ConstentUtil.strToList(Integer.toString(companyId)));

            Map<String,Object> returnMapList=new HashMap<String,Object>();
            //将用户信息放入map
            returnMapList.put("id",tUser.getId());
            returnMapList.put("userName",tUser.getUserName());
            returnMapList.put("loginName",tUser.getLoginName());
            returnMapList.put("password",tUser.getPassword());
            returnMapList.put("phone", tUser.getPhone());

            //将角色信息放入集合
            List<Map<String,Object>> inputList=new ArrayList<Map<String,Object>>();
            if(!ConstentUtil.isEmpty(tRoleList)){
                for(Map<String,Object> tRoles : tRoleList){

                    Integer allRoleId= (Integer) tRoles.get("roleId");

                    Map<String,Object> roleMap=new HashMap<>();
                    roleMap.put("roleId",(Integer)tRoles.get("roleId"));
                    roleMap.put("rName",tRoles.get("rName"));
                    roleMap.put("rCode",tRoles.get("rCode"));
                    roleMap.put("roleState",tRoles.get("roleState"));
                    roleMap.put("roleSerial",tRoles.get("serial"));
                    roleMap.put("RoleDescription",tRoles.get("description"));
                    roleMap.put("roleUpdateTime",tRoles.get("rolUpdateTime"));

                    if(!ConstentUtil.isEmpty(tRoleLists)){
                        for(Map<String,Object> rMap : tRoleLists){
                            Integer partRoleId=(Integer) rMap.get("roleId");
                            //添加用户含有的角色信息到map，并且为其添加属性selected ： true
                            if(allRoleId.equals(partRoleId)){
                                roleMap.put("selected","1");
                                break;
                            }else{
                                roleMap.put("selected","0");
                            }
                        }
                    }else{
                        roleMap.put("selected","0");
                    }
                    inputList.add(roleMap);
                }
            }
            returnMapList.put("roleList",inputList);
            logger.info("查询用户角色信息成功:{}",returnMapList);
            return ResponseResult.success(returnMapList);
        } catch (Exception e) {
            logger.error("查询用户角色信息异常",e);
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }


    /**
     * 根据用户信息查询用户与角色的关联信息
     * @param jsonObject 用户信息
     * @return  符合查询条件用户与角色的相关信息列表
     */
    @ApiOperation(value="根据用户信息查询用户与角色的关联信息", notes="根据用户信息查询用户与角色的关联信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID"),
            @ApiImplicitParam(name = "userName", value = "用户名称"),
            @ApiImplicitParam(name = "loginName", value = "登录名"),
            @ApiImplicitParam(name = "phone", value = "手机号"),
            @ApiImplicitParam(name = "createTime", value = "创建时间"),
            @ApiImplicitParam(name = "updateTime", value = "修改时间")
    })
    @PostMapping("getUserRoleInfoListByUserCondition")
    public ResponseResult getUserRoleInfoListByUserCondition(@RequestBody JSONObject jsonObject) throws Exception {

        List<Map<String,Object>> all_list = new ArrayList<Map<String,Object>>();
        TUser tUser= (TUser) ConstentUtil.json2Object(jsonObject,TUser.class);
        try {
            //根据条件查询用户信息列表
            List<TUser> resourceList=tUserService.getUserInfoListByCondition(tUser);
            if(!ConstentUtil.isEmpty(resourceList)){
                String stringBuffer="";
                for(TUser user : resourceList){
                    stringBuffer +=user.getId()+",";
                }
                stringBuffer= stringBuffer.substring(0,stringBuffer.length()-1).trim();
                List li=ConstentUtil.strToList(stringBuffer);

                List<Map<String,Object>> tRoleList= tRoleService.selectTRoleInfoListByUserId(li);
                if(!ConstentUtil.isEmpty(tRoleList)){

                    String[] strs = stringBuffer.split(",");
                    for (int j = 0; j < strs.length; j++) {
                        HashMap<String, Object> hm = new HashMap<>();
                        List list1 = new ArrayList();
                        for (int i = 0; i < tRoleList.size(); i++) {
                            if(strs[j].equals(tRoleList.get(i).get("userId").toString())) {
                                hm.put("userId", strs[j]);
                                hm.put("userName", tRoleList.get(i).get("userName").toString());
                                hm.put("loginName", tRoleList.get(i).get("loginName").toString());
                                list1.add(tRoleList.get(i));
                                hm.put("data",list1);
                            }
                        }
                        if(hm.size()!=0){
                            all_list.add(hm);
                        }
                    }
                }
            }
            logger.info("查询用户与角色信息成功:{}",all_list);
            return ResponseResult.success(all_list);
        } catch (Exception e) {
            logger.error("查询用户与角色信息异常:",e);
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }
}
